from typing import Dict, Any
from agents.rag_agent import RAGAgent
from config import STAGES, REWARDS, INTENT_PROMPT
from langchain_core.messages import HumanMessage
from langchain_openai import ChatOpenAI
import os

class OnboardingAgent:
    def __init__(self):
        self.current_stage_index = 0
        self.rag_agent = RAGAgent()
        self.llm = self.create_llm()

    def create_llm(self) -> ChatOpenAI:
        """创建并返回配置好的大模型实例"""
        return ChatOpenAI(
            api_key=os.getenv("DASHSCOPE_API_KEY") or "your_api_key_here",
            base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
            model="qwen2.5-math-72b-instruct"
        )

    def get_current_stage(self):
        return STAGES[self.current_stage_index] if self.current_stage_index < len(STAGES) else None

    '''根据用户输入，通过LLM判断用户的意图
    返回值：
        stage_complete：用户旅程的某个阶段完成
        product_inquiry：产品咨询
        general_conversation： 闲聊
    '''

    def detect_intent_with_llm(self, user_input: str) -> str:
        # 使用模板构建 Prompt
        prompt = INTENT_PROMPT.format(user_input=user_input)

        # 调用模型
        try:
            response = self.llm.invoke([HumanMessage(content=prompt)])
            intent = response.content.strip().replace('\n\\end{document}', '').strip("'").strip('"').strip('`')

            # 确保返回值在指定范围内
            if intent == "stage_complete":
                return "stage_complete"
            elif intent == "product_inquiry":
                return "product_inquiry"
            else:
                return "general_conversation"
        except Exception as e:
            print("调用大模型失败，使用默认逻辑。错误：", e)
            # 失败时兜底逻辑
            if any(kw in user_input.lower() for kw in ["已注册", "已开户", "已入金", "已交易"]):
                return "stage_complete"
            elif any(kw in user_input.lower() for kw in ["手续费", "安全", "优惠", "选股"]):
                return "product_inquiry"
            else:
                return "general_conversation"

    def process_input(self, user_input: str) -> Dict[str, Any]:
        current_stage = self.get_current_stage()
        if not current_stage:
            return {"type": "onboarding_complete"}

        # 大模型根据用户输入进行意图检测
        intent = self.detect_intent_with_llm(user_input)

        # 如果是完成某个用户旅程的某个阶段
        if intent == "stage_complete":
            self.current_stage_index += 1
            next_stage = self.get_current_stage()
            if next_stage:
                return {
                    "type": "stage_progression",
                    "content": f"太好了！现在进入【{next_stage}】阶段，可得{REWARDS[next_stage]}。",
                    "next_stage": next_stage
                }
            else:
                return {
                    "type": "onboarding_complete",
                    "content": "恭喜完成所有阶段！"
                }
        # 如果用户意图是产品咨询，走RAG查询
        elif intent == "product_inquiry":
            rag_response = self.rag_agent.handle_query(user_input, current_stage)
            return rag_response

        # 如果是闲聊，引导完成用户流程往下走
        else:
            return {
                "type": "general_conversation",
                "content": f"关于这个问题，我需要一点时间思考。同时提醒您尚未完成【{current_stage}】阶段，此阶段可获{REWARDS[current_stage]}"
            }